<?php

namespace App\Utility;

use App\Model\Message\MessageBean;
use App\Model\User\UserModel;
use App\Server\SwooleServer;
use EasySwoole\Core\Component\Logger;
use Swoole\Server;

class Common {
	public function broadcast($message) {
		
		// 处理广播要用死循环 不要把所有的fd都取出来这样浪费内存每次去一定的数量循环处理
		$start_fd = 0;
		$offest = 10;
		$swooleserver = (new SwooleServer ());
		$server = $swooleserver->getServer ();
		while ( true ) {
			$clist = $server->connection_list ( $start_fd, $offest );
			if ($clist === false or count ( $clist ) === 0) {
				break;
			}
			$start_fd = end ( $clist );
			if ($clist) {
				foreach ( $clist as $k => $v ) {
					$fd = intval ( $v );
					if ($fd > 0) {
						$info = $server->connection_info ( $fd );
						if (is_array ( $info ) && $info ['websocket_status'] == 3) {
							$swooleserver->push ( $fd, $message );
						}
					}
				}
			}
		}
	}
	public function onLineNum() {
		return (new UserModel ())->getOnlineNum ();
	}
	public function pushMessage($fd, $msg) {
		$swooleserver = (new SwooleServer ());
		if (intval ( $fd ) > 0) {
			$server = $swooleserver->getServer ();
			$info = $server->connection_info ( $fd );
			if (is_array ( $info ) && $info ['websocket_status'] == 3) {
				$swooleserver->push ( $fd, $msg );
			}
		}
	}
	public function pushMessageToFriends($fds, $msg) {
		if ($fds) {
			$swooleserver = (new SwooleServer ());
			foreach ( $fds as $k => $fd ) {
				if (intval ( $fd ) > 0) {
					$server = $swooleserver->getServer ();
					$info = $server->connection_info ( $fd );
					if (is_array ( $info ) && $info ['websocket_status'] == 3) {
						$swooleserver->push ( $fd, $msg );
					}
				}
			}
		}
	}
	public function E($str, $saveLog = 1) {
		Logger::getInstance ()->console ( $str, $saveLog );
	}
	public function dealMessage($statusCode, MessageBean $message, $msg = "") {
		$data = Array (
				"code" => $statusCode,
				"result" => $message->objToArray ( true ),
				"msg" => $msg 
		);
		return json_encode ( $data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
	}
	public function isOnline($fd) {
		$fd = intval ( $fd );
		if ($fd <= 0) {
			return false;
		}
		$swooleserver = (new SwooleServer ());
		$server = $swooleserver->getServer ();
		$info = $server->connection_info ( $fd );
		if (is_array ( $info ) && $info ['websocket_status'] == 3) {
			return true;
		} else {
			return false;
		}
	}
}